// @Title 微信相关
// @Description 请填写文件描述
// @Author 赵伟 2020/11/27 17:20

package wechat

import (
    "authserver/global"
    "authserver/model"
    "encoding/json"
    "errors"
    "io/ioutil"
    "net/http"
    "time"
)

var (
	// 发布的时候注意，这里用走了 代理访问的 nginx 代理
	HostOpenidName      = "https://api.weixin.qq.com/sns/jscode2session?"
	HostAccessTokenName = "https://api.weixin.qq.com/cgi-bin/token?"
	HostUnlimitedName   = "https://api.weixin.qq.com/wxa/getwxacodeunlimit?"
)

var (
	ErrAppIDNotMatch       = errors.New("app id not match")
	ErrInvalidBlockSize    = errors.New("invalid block size")
	ErrInvalidPKCS7Data    = errors.New("invalid PKCS7 data")
	ErrInvalidPKCS7Padding = errors.New("invalid padding on input")
)

// 线条颜色
type LineColor struct {
	R int
	G int
	B int
}

// 获取微信个人信息
type WxUserInfo struct {
	OpenID    string `json:"openId"`
	UnionID   string `json:"unionId"`
	NickName  string `json:"nickName"`
	Gender    int    `json:"gender"`
	City      string `json:"city"`
	Province  string `json:"province"`
	Country   string `json:"country"`
	AvatarURL string `json:"avatarUrl"`
	Language  string `json:"language"`
	Watermark struct {
		Timestamp int64  `json:"timestamp"`
		AppID     string `json:"appid"`
	} `json:"watermark"`
}

// 获取手机号
type WxUserPhone struct {
	PhoneNumber     string `json:"phoneNumber"`
	PurePhoneNumber string `json:"purePhoneNumber"`
	CountryCode     string `json:"countryCode"`
	Watermark       struct {
		Timestamp int64  `json:"timestamp"`
		AppID     string `json:"appid"`
	} `json:"watermark"`
}

type WXUserDataCrypt struct {
	appID, sessionKey string
}

// 初始化请求信息
func NewWXUserDataCrypt(appID, sessionKey string) *WXUserDataCrypt {
	return &WXUserDataCrypt{
		appID:      appID,
		sessionKey: sessionKey,
	}
}

// pkcs7Unpad返回不带填充的原始数据片段
func pkcs7Unpad(data []byte, blockSize int) ([]byte, error) {
	if blockSize <= 0 {
		return nil, ErrInvalidBlockSize
	}
	if len(data)%blockSize != 0 || len(data) == 0 {
		return nil, ErrInvalidPKCS7Data
	}
	c := data[len(data)-1]
	n := int(c)
	if n == 0 || n > len(data) {
		return nil, ErrInvalidPKCS7Padding
	}
	for i := 0; i < n; i++ {
		if data[len(data)-n+i] != c {
			return nil, ErrInvalidPKCS7Padding
		}
	}
	return data[:len(data)-n], nil
}

// GetUserOpenID @Title 获取用户openid
// @Description 函数的详细描述
// @Author 赵伟 2020/11/26 14:37
// @Param
// @Return
func GetUserOpenID(appId,code string) (err error, param map[string]interface{}) {
	client := &http.Client{Timeout: 5 * time.Second}

    var weiInfo model.SysConfig
    global.GVA_DB.Table(weiInfo.TableName()).Where("config_key = ?",appId).Find(&weiInfo)
    if weiInfo.Id==0{
        err = errors.New("登录失败")
        return
    }

	resp, err := client.Get(HostOpenidName + "appid=" + appId + "&secret=" + weiInfo.Param1 + "&js_code=" + code + "&grant_type=authorization_code")
	if err != nil {
		global.GVA_LOG.Error(err.Error())
		return errors.New("无法访问外部服务器"), param
	}

	body, err := ioutil.ReadAll(resp.Body)
	if err != nil {
		return err, param
	}
	param = make(map[string]interface{})
	_ = json.Unmarshal(body, &param)
	return err, param
}
